import os
import dash
from dash import html
from flask import request
import feffery_antd_components as fac
from dash.dependencies import Input, Output

app = dash.Dash(__name__)


# 这里的app即为Dash实例
@app.server.route('/upload/', methods=['POST'])
def upload():
    '''
    构建文件上传服务
    :return:
    '''

    # 获取上传id参数，用于指向保存路径
    uploadId = request.values.get('uploadId')

    # 获取上传的文件名称
    filename = request.files['file'].filename

    # 基于上传id，若本地不存在则会自动创建目录
    try:
        os.mkdir(os.path.join('assets', uploadId))
    except FileExistsError:
        pass

    # 流式写出文件到指定目录
    with open(os.path.join('assets', uploadId, filename), 'wb') as f:
        # 流式写出大型文件，这里的10代表10MB
        for chunk in iter(lambda: request.files['file'].read(1024 * 1024 * 10), b''):
            f.write(chunk)

    return {'filename': filename}


app.layout = html.Div(
    [
        fac.AntdUpload(
            id='pdf-upload',
            apiUrl='/upload/',
            buttonContent='请上传pdf文件',
            fileTypes=['pdf'],
            fileListMaxLength=1
        ),

        html.Div(
            id='pdf-render',
            style={
                'height': '800px',
                'display': 'flex',
                'alignItems': 'center',
                'justifyContent': 'center',
                'marginTop': '25px'
            }
        )
    ],
    style={
        'padding': '25px'
    }
)


@app.callback(
    Output('pdf-render', 'children'),
    Input('pdf-upload', 'lastUploadTaskRecord')
)
def render_pdf(lastUploadTaskRecord):
    if lastUploadTaskRecord:
        return html.Iframe(
            src='/assets/{}/{}'.format(lastUploadTaskRecord['taskId'], lastUploadTaskRecord['fileName']),
            style={
                'height': '100%',
                'width': '100%',
                'border': 'none'
            }
        )

    return fac.AntdEmpty(
        description='请先上传pdf文件'
    )


if __name__ == '__main__':
    app.run_server(debug=True)